package com.wg.db.repository.code;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 异步MySQL仓库（Map存储版）
 *
 * @param <Key> 实体ID类型
 * @param <T>   实体类型
 */
public class MySqlAsyncMapRepository<Key extends Serializable, T> extends AbstractMySqlAsyncRepository<Key, T> {
    private final HashMap<Key, DataWrapper<Key, T>> map = new HashMap<>();

    public MySqlAsyncMapRepository(Class<T> entityClass) {
        super(entityClass);
    }

    @Override
    protected void addDataWrapper(DataWrapper<Key, T> dataWrapper) {
        map.put(dataWrapper.getKey(), dataWrapper);

    }

    @Override
    public int pendingSize() {
        return map.size();
    }

    @Override
    protected List<DataWrapper<Key, T>> getAllEntities() {
        if (map.size() <= batchSize) {
            return new ArrayList<>(map.values());
        } else {
            List<DataWrapper<Key, T>> executeDatas = new ArrayList<>();
            for (DataWrapper<Key, T> wrapper : map.values()) {

                executeDatas.add(wrapper);
                if (executeDatas.size() >= batchSize) {
                    break;
                }
            }
            return executeDatas;
        }
    }

    @Override
    protected void onSuccess(List<DataWrapper<Key, T>> successDatas) {
        for (DataWrapper<Key, T> dataWrapper : successDatas) {
            map.remove(dataWrapper.getKey());
        }
    }

    @Override
    protected void onFail(List<DataWrapper<Key, T>> failDatas) {
    }
}
